package array;

/**
 * description:稀疏数组的练习  <br>
 * date: 2022/1/14 21:00 <br>
 * version: 1.0 <br>
 *
 * @author Tansty
 */

public class SparseArray {
    /**
     * @param array
     * @Description 二维数组转稀疏数组
     * @author Tansty
     * @date 2022/1/14 21:01
     */
    public static void arrayToSparse(int[][] array) {
        int number = 0;
        for (int[] i : array) {
            for (int item : i) {
                if (item != 0) {
                    number++;
                }
            }
        }
        int[][] sparse = new int[number + 1][3];
        sparse[0][0] = array.length;
        sparse[0][1] = array[0].length;
        sparse[0][2] = number;
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    count++;
                    sparse[count][0] = i;
                    sparse[count][1] = j;
                    sparse[count][2] = array[i][j];
                }
            }
        }
        for (int[] item : sparse) {
            System.out.printf("%d\t%d\t%d\t\n", item[0], item[1], item[2]);
        }
    }

    /**
     * @param sparse
     * @Description 稀疏数组转换为二维数组
     * @author Tansty
     * @date 2022/1/14 21:28
     */
    public static void sparseToArray(int[][] sparse) {
        int[][] array = new int[sparse[0][0]][sparse[0][1]];
        for (int i = 1; i < sparse.length; i++) {
            array[sparse[i][0]][sparse[i][1]] = sparse[i][2];
        }
        for (int[] item : array) {
            for (int i : item) {
                System.out.printf("%d\t", i);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] array = new int[][]{{11, 11, 2}, {1, 2, 1}, {2, 4, 2}};
        sparseToArray(array);
    }
}
